/**
 * ajax基础封装
 * @module ajax
 */
define("ajax", [], function(Lyx){

	"user strict";

	/**
	 * @callback ajaxCallBack
	 * @param {XMLHttpRequest} xhr 返回数据
	 * @param {string} response 接受返回的字符串
	 */


	/**
	 * ajax操作
	 * @alias module:ajax
	 * @param {object} request 请求对象
	 * @param {string} request.url 请求地址
	 * @param {string} [request.data] 发送数据
	 * @param {string} [request.method = "get"] 请求方式，get | post
	 * @param {ajaxCallBack} [callBack] 服务器返回时的回调函数
	 * @param {object} [context] callback的函数上下文，未设置时为this
	 */
	function ajax(request, callBack, context)
	{
		if(Lyx.isFunction(callBack))
		{
			context = this;
		}
		else
		{
			if(Lyx.isUndefined(callBack))
			{
				context = this;
			}
			else
			{
				context = callBack;
			}
			callBack = function()
			{
				Lyx.log("ajax回调函数执行！");
			}
		}
		var xhr = "";
		try
		{
			xhr = new XMLHttpRequest();
		} 
		catch(e)
		{
			try
			{
				xhr = new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch(e)
			{
				try
				{
					xhr = new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch(e){}
			}
		}
		xhr.onreadystatechange = function()
		{
			if (xhr.readyState == 4)
			{
				if (xhr.status == 200)
				{
					var response = xhr.responseText.trim();
					callBack.call(context, xhr, response);
				}
				else
				{
					console.error("通信异常：%s\n状态码：%s", request.url, xhr.status);
				}
			}
		};
		request.method = request.method || "GET";
		request.method = request.method.toLocaleUpperCase();
		var data = "";
		for(i in request.data)
		{
			data += i + "=" + encodeURIComponent(request.data[i]) + "&";
		}
		data = data.substring(0, data.length - 1);
		if(request.method == "GET")
		{
			Lyx.log(request.url + "?" + data);
			xhr.open(request.method, request.url + "?" + data, true);
			xhr.send(null);
		}
		else if(request.method == "POST")
		{
			Lyx.log(request.url);
			xhr.open(request.method, request.url, true);
			xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xhr.send(data);
		}
		else
		{
			console.error("method非法！");
		}
	}
	return ajax;
});